package mq.demo2;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

public class TopicConsumerDemo {
    public static void main(String[] args) throws JMSException, IOException {
        String brokerURL="tcp://192.168.100.100:61616";
        // 工厂
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(brokerURL);
        // 连接对象
        Connection connection = activeMQConnectionFactory.createConnection("admin", "admin");
        // 连接
        connection.start();
        // 第一个参数: 是否开启事务,第二个参数:应答模式
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic testTopic = session.createTopic("test_topic");

        // 创建消费者
        MessageConsumer consumer = session.createConsumer(testTopic);

       // TextMessage message = (TextMessage) consumer.receive();
       // System.out.println("收到消息:" + message.getText() );

        consumer.setMessageListener(new MessageListener() {
            // onMessage的方法会在有消息的时候,自动执行
            public void onMessage(Message message) {
                if(message instanceof TextMessage){
                    TextMessage textMessage = (TextMessage) message;
                    try {
                        System.out.println("收到文本消息:" + textMessage.getText() );
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }else if(message instanceof ObjectMessage){
                    ObjectMessage objectMessage = (ObjectMessage) message;
                    try {
                        System.out.println("收到文本消息:" + objectMessage.getObject().toString() );
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        System.in.read();
        consumer.close();
        session.close();
        connection.close();
    }
}
